package com.jsbb.runner;

import com.jsbb.config.ParamsConfig;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * MinIO
 *
 * @author w
 * @date 2021-03-05
 */
@Slf4j
@Component
@Order(value = 1)
public class MinioBucketRunner implements CommandLineRunner {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private ParamsConfig paramsConfig;

    private static String policyJson = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::#bucket\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::#bucket/*\"]}]}";

    @Override
    public void run(String... args) {
        String bucket = paramsConfig.getMinioBucket();
        if (bucket == null) {
            return;
        }
        try {
            //判断存储桶是否存在
            boolean bucketIsExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
            if (!bucketIsExist) {
                //创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
                //设置存储桶策略
                String config = policyJson.replaceAll("#bucket", bucket);
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucket).config(config).build());
            }
        } catch (Exception e) {
            log.error("初始化存储桶异常==={}", e.getMessage());
        }
    }
}
